package com.opc.quarz;

import com.opc.Service.OpcUaService;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.milo.opcua.sdk.client.OpcUaClient;
import org.eclipse.milo.opcua.stack.core.UaException;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.stereotype.Component;
import java.util.*;
@Component
@Slf4j
//@DisallowConcurrentExecution // 确保任务不会并发执行            //实现Job 接口，以便于在其他地方调用
public class InsertHingeScrewDataQuartz extends QuartzJobBean implements Job {

    @Autowired
    private OpcUaService opcUaService;

    @Override
    protected void executeInternal(JobExecutionContext context) {
        OpcUaClient client = null;
        List<String> nodeIdList = new ArrayList<>();

        try {
            // 1. 创建客户端并连接
            client = opcUaService.createClient();
            client.connect().get();

            // 2. 浏览节点
            String[] nodeIds = opcUaService.browseNode(client, null);
            //log.info("检测到的可用节点: " + Arrays.toString(nodeIds));

            if (nodeIds != null) {
//                for (String nodeId : nodeIds) {
//                    nodeIdList.add(nodeId);
//                }
                nodeIdList.addAll(Arrays.asList(nodeIds));
            }
//            else {
//                log.info("nodeIds 为空");
//            }

            // 3. 订阅
            opcUaService.subscribe(client, nodeIdList);

        } catch (UaException e) {
//            if (e.getStatusCode().getValue() == StatusCode.get) {
                // 会话关闭，重新创建并重试一次
                try {
                    log.info("捕获 Bad_SessionClosed 异常，尝试重连...");
                    if (client != null) {//断开会话，避免资源泄漏
                        client.disconnect().get();
                    }
                    client = opcUaService.createClient();
                    client.connect().get();
                    opcUaService.subscribe(client, nodeIdList);
                } catch (Exception ex) {
                    ex.printStackTrace();
                    // 日志或报警
                }
//            } else {
//                throw new RuntimeException(e);
//            }
        } catch (Exception e) {
//            e.printStackTrace();
            // 其他异常，尝试断开并抛出
            try {
                if (client != null) {//断开会话，避免资源泄漏
                    client.disconnect().get();
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
//            throw new RuntimeException(e);
        } finally {
            // 结束时建议断开连接释放资源
            try {
                if (client != null) {//断开会话，避免资源泄漏
                    client.disconnect().get();
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

//    @Override
//    protected void executeInternal(JobExecutionContext context){
//        OpcUaClient client = null;
//        List<String> nodeIdList = new ArrayList<>();
//        try {
//            //确保在读写之前 创建好这个连接
//            client = opcUaService.createClient();
//            client.connect().get();
//            String[] nodeIds = opcUaService.browseNode(client,null);
//            log.info("检测到的可用节点: " + Arrays.toString(nodeIds));
//
////            NodeId[] stringIds = new NodeId[nodeIds.length]; // 创建同样长度的 String 数组
////
////            for (int i = 0; i < nodeIds.length; i++) {
////                stringIds[i] = NodeId.parse(nodeIds[i]); // 将每个 NodeId 转换为字符串
////            }
//
//            // 使用列表手动将 NodeId 逐个添加到新节点数组
//            // 这里的 list 用于临时保存动态添加的 NodeId 对象
////            List<String> nodeIdList = new ArrayList<>();
//            if(nodeIds != null){
//                 for (String nodeId : nodeIds) {
//                  // 打印每个 NodeId
////                log.info("处理 NodeId: " + nodeId);
//                // 将每个 NodeId 添加到 List 中
//                 nodeIdList.add(nodeId); // 添加到列表
//                 }
//            }else {
//                log.info("nodeIds 为空");
//            }
//
//
////            // 将 List 转换为 NodeId 数组
////            NodeId[] newNodeIds = nodeIdList;
////            log.info("转换后的 NodeId 数组: " + Arrays.toString(newNodeIds));
//
////            Object nodeIdsData = CacheUtil.getFromCache("nodeIdsData");
////            log.info("nodeIdsData: " + nodeIdsData);
////            while (nodeIdsData == "0" || nodeIdsData == null){
//
//            opcUaService.subscribe(client, nodeIdList);
////                // 休眠 2 秒 (2000 毫秒) 等待数据可能更新
////                Thread.sleep(2000);
////                nodeIdsData = CacheUtil.getFromCache("nodeIdsData");
////            }
//// 关闭连接（断开会话）
//        } catch (UaException e) {
//            if (e.getStatusCode().getValue() == StatusCode.BAD_SESSION_CLOSED) {
//                // 会话关闭，重新连接并重试一次
//                try {
//                    client = opcUaService.createClient();
//                    opcUaService.subscribe(client, nodeIdList);
//                } catch (Exception ex) {
//                    // 记录日志、报警或抛出
//                }
//            } else {
//                throw new RuntimeException(e);
//            }
//        } catch (Exception e) {
//            log.info("抛出异常");
//            try {
//                if (client != null) {
//                    client.disconnect().get();
//                }
//                opcUaService.subscribe(client, nodeIdList);
//            } catch (Exception ex) {
//                throw new RuntimeException(ex);
//            }
//
//            throw new RuntimeException(e);
//        }
//    }

}
